<?php

class InquiryBox extends AbstractBox {
	protected $template = 'inquiry/box.tpl';
	
	protected function setup() {
		if ($_POST['answer']) {
			// otestujeme ci user s danou IP este v danej ankete nehlasoval
			$voterRepository = new VoterRepository();
			$voter = $voterRepository->getOneByUserIpAndFkQuestionId($_SERVER['REMOTE_ADDR'], intval($_POST['question']));
			if ($voter) {
				// uz si hlasoval
			} else {
				// zapiseme hlas
				$data = array(
					'pid' => intval($GLOBALS['TSFE']->config['config']['votersPid']),
					'crdate' => time(),
					'tstamp' => time(),
					'user_browser' => $_SERVER['HTTP_USER_AGENT'],
					'user_ip' => $_SERVER['REMOTE_ADDR'],
					'fk_question_id' => intval($_POST['question']),
					'fk_answer_id' => intval($_POST['answer']),
				);
				$voter = new Voter($data);
				$voter->save();

				// navysime pocet hitov pre otazku
				$questionRepository = new QuestionRepository();
				$question = $questionRepository->getOneByUid(intval($_POST['question']));
				$question['hits'] = $question['hits'] + 1;
				$question->save();

				// navysime pocet hitov pre odpoved
				$answerRepository = new AnswerRepository();
				$answer = $answerRepository->getOneByUid(intval($_POST['answer']));
				$answer['hits'] = $answer['hits'] + 1;
				$answer->save();
			}
		}
		
		// vyberieme hlasy podla IP
		$voterRepository = new VoterRepository();
		$votes = $voterRepository->getByUserIp($_SERVER['REMOTE_ADDR']);
		
		$votedQuestions = array();
		foreach ($votes as $vote) {
			$votedQuestions[] = $vote['fk_question_id'];
		}
		
		// vyberieme naposledy zmenenu otazku v ktorej este user nehlasoval
		$questionRepository = new QuestionRepository();
		$questionRepository->setOrderBy(array('tstamp' => 'desc'));
		
		// TODO starttime endtime
		
		if ($votedQuestions) {
			$questionRepository->addAdditionalWhere(array('column' => 'uid', 'value' => $votedQuestions, 'xxx' => '!='));
		}
		$question = $questionRepository->getOneBy();

		MySmarty::assign('question', $question);
	}
}

?>